package com.example.lcpractice.lc;

import com.example.lcpractice.datastructure.TreeNode;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 114. 二叉树展开为链表
 * 中等
 * 1.3K
 * 相关企业
 * 给你二叉树的根结点 root ，请你将它展开为一个单链表：
 * <p>
 * 展开后的单链表应该同样使用 TreeNode ，其中 right 子指针指向链表中下一个结点，而左子指针始终为 null 。
 * 展开后的单链表应该与二叉树 先序遍历 顺序相同。
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * <p>
 * 输入：root = [1,2,5,3,4,null,6]
 * 输出：[1,null,2,null,3,null,4,null,5,null,6]
 * 示例 2：
 * <p>
 * 输入：root = []
 * 输出：[]
 * 示例 3：
 * <p>
 * 输入：root = [0]
 * 输出：[0]
 * <p>
 * <p>
 * 提示：
 * <p>
 * 树中结点数在范围 [0, 2000] 内
 * -100 <= Node.val <= 100
 */
public class Lc114 {

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(11);

        TreeNode node2 = new TreeNode(21);
        TreeNode node3 = new TreeNode(22);
        node1.left = node2;
        node1.right = node3;

        TreeNode node4 = new TreeNode(31);
        TreeNode node5 = new TreeNode(32);
        node2.left = node4;
        node2.right = node5;
//        TreeNode node5 = new TreeNode(3);
        TreeNode node6 = new TreeNode(33);
        node3.right = node6;

        flatten(node1);
    }

    public static void flatten(TreeNode root) {
        Queue<TreeNode> queue = new ArrayDeque<>();
        recursion(root, queue);
        TreeNode temp = root;

        if (queue.size() > 1) {
            queue.poll();
            root.left = null;
            while (!queue.isEmpty()) {
                TreeNode treeNode = queue.poll();
                temp.right = treeNode;
                treeNode.left = null;
                temp = treeNode;
            }

        }
    }

    private static void recursion(TreeNode root, Queue<TreeNode> queue) {
        if (root != null) {
            queue.add(root);
            recursion(root.left, queue);
            recursion(root.right, queue);
        }
    }


    public static void flatten2(TreeNode root) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        stack.push(root);
        TreeNode prev = null;
        while (!stack.isEmpty()) {
            TreeNode curr = stack.pop();
            if (prev != null) {
                prev.left = null;
                prev.right = curr;
            }
            TreeNode left = curr.left, right = curr.right;
            if (right != null) {
                stack.push(right);
            }
            if (left != null) {
                stack.push(left);
            }
            prev = curr;
        }
    }


}



